<!DOCTYPE HTML>
<html lang="en-US" manifest="../manifest.appcache">
    
    <head prefix="og: http://ogp.me/ns# book: http://ogp.me/ns/book#">
        
        
        <meta charset="UTF-8">
        <title>《The Swift Programming Language》中文版</title>

        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <meta name="robots" content="index, follow">
        <meta name="author" content="">
        <meta name="description" content="Swift 中文翻译组：364279588（要求对翻译感兴趣）">
        <meta name="keywords" content="gitbook,github" >
        <meta name="generator" content="www.gitbook.io">

        
        <link rel="next" href="../chapter2/13_Inheritance.html" />
        
        
        <link rel="prev" href="../chapter2/11_Methods.html" />
        

        <meta property="og:title" content="附属脚本 | 这一次，让中国和世界同步">
        <meta property="og:site_name" content="这一次，让中国和世界同步">
        <meta property="og:type" content="book">
        <meta property="og:locale" content="en_US">

        <meta property="book:author" content="https://github.com/">
        <meta property="book:tag" content="GitBook">

        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
        <meta name="apple-mobile-web-app-capable" content="yes">
        <meta name="apple-mobile-web-app-status-bar-style" content="black">

        <link rel="shortcut icon" href="../gitbook/images/favicon.ico" type="image/x-icon">
        
        
    </head>
    <body>
        
        

        <link rel="stylesheet" href="../gitbook/style.css">
        


        
    <div class="book"  data-level="2.12" data-basepath=".." data-revision="1402523087598">
    <div class="book-header">
    <!-- Actions Left -->
    <a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
    
    <a href="https://github.com/null" target="_blank" class="btn pull-left home-bookmark" aria-label="GitHub home"><i class="fa fa-bookmark-o"></i></a>
    
    <a href="#" class="btn pull-left toggle-search" aria-label="Toggle search"><i class="fa fa-search"></i></a>
    <span id="font-settings-wrapper">
        <a href="#" class="btn pull-left toggle-font-settings" aria-label="Toggle font settings"><i class="fa fa-font"></i>
        </a>
        <div class="dropdown-menu font-settings">
    <div class="dropdown-caret">
        <span class="caret-outer"></span>
        <span class="caret-inner"></span>
    </div>

    <div class="btn-group btn-block">
        <button id="reduce-font-size" class="btn btn-default">A</button>
        <button id="enlarge-font-size" class="btn btn-default">A</button>
    </div>

    <ul class="list-group font-family-list">
        <li class="list-group-item" data-font="0">Serif</li>
        <li class="list-group-item" data-font="1">Sans</li>
    </ul>

    <div class="btn-group btn-group-xs btn-block color-theme-list">
        <button type="button" class="btn btn-default" id="color-theme-preview-0" data-theme="0">White</button>
        <button type="button" class="btn btn-default" id="color-theme-preview-1" data-theme="1">Sepia</button>
        <button type="button" class="btn btn-default" id="color-theme-preview-2" data-theme="2">Night</button>
    </div>
</div>

    </span>

    <!-- Actions Right -->
    
    <a href="#" target="_blank" class="btn pull-right google-plus-sharing-link sharing-link" data-sharing="google-plus" aria-label="Share on Google Plus"><i class="fa fa-google-plus"></i></a>
    
    
    <a href="#" target="_blank" class="btn pull-right facebook-sharing-link sharing-link" data-sharing="facebook" aria-label="Share on Facebook"><i class="fa fa-facebook"></i></a>
    
    
    <a href="#" target="_blank" class="btn pull-right twitter-sharing-link sharing-link" data-sharing="twitter" aria-label="Share on Twitter"><i class="fa fa-twitter"></i></a>
    

    

    <!-- Title -->
    <h1>
        <i class="fa fa-spinner fa-spin"></i>
        <a href="../" >这一次，让中国和世界同步</a>
    </h1>
</div>

    

<div class="book-summary">
    <div class="book-search">
        <input type="text" placeholder="Search" class="form-control" />
    </div>
    <ul class="summary">
        
        

        

        

        

        <li data-level="0" data-path="index.html">
            <a href="../"><i class="fa fa-check"></i> 序</a>
        </li>
        
    
        <li class="chapter " data-level="1" data-path="chapter1/chapter1.html">
            
            <a href="../chapter1/chapter1.html">
                <i class="fa fa-check"></i> <b>1.</b> 欢迎使用 Swift
            </a>
            
            
            <ul class="articles">
                
    
        <li class="chapter " data-level="1.1" data-path="chapter1/01_swift.html">
            
            <a href="../chapter1/01_swift.html">
                <i class="fa fa-check"></i> <b>1.1.</b> 关于 Swift
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="1.2" data-path="chapter1/02_a_swift_tour.html">
            
            <a href="../chapter1/02_a_swift_tour.html">
                <i class="fa fa-check"></i> <b>1.2.</b> Swift 初见
            </a>
            
            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="2" data-path="chapter2/chapter2.html">
            
            <a href="../chapter2/chapter2.html">
                <i class="fa fa-check"></i> <b>2.</b> Swift 教程
            </a>
            
            
            <ul class="articles">
                
    
        <li class="chapter " data-level="2.1" data-path="chapter2/01_The_Basics.html">
            
            <a href="../chapter2/01_The_Basics.html">
                <i class="fa fa-check"></i> <b>2.1.</b> 基础部分
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.2" data-path="chapter2/02_Basic_Operators.html">
            
            <a href="../chapter2/02_Basic_Operators.html">
                <i class="fa fa-check"></i> <b>2.2.</b> 基本运算符
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.3" data-path="chapter2/03_Strings_and_Characters.html">
            
            <a href="../chapter2/03_Strings_and_Characters.html">
                <i class="fa fa-check"></i> <b>2.3.</b> 字符串和字符
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.4" data-path="chapter2/04_Collection_Types.html">
            
            <a href="../chapter2/04_Collection_Types.html">
                <i class="fa fa-check"></i> <b>2.4.</b> 集合类型
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.5" data-path="chapter2/05_Control_Flow.html">
            
            <a href="../chapter2/05_Control_Flow.html">
                <i class="fa fa-check"></i> <b>2.5.</b> 控制流
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.6" data-path="chapter2/06_Functions.html">
            
            <a href="../chapter2/06_Functions.html">
                <i class="fa fa-check"></i> <b>2.6.</b> 函数
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.7" data-path="chapter2/07_Closures.html">
            
            <a href="../chapter2/07_Closures.html">
                <i class="fa fa-check"></i> <b>2.7.</b> 闭包
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.8" data-path="chapter2/08_Enumerations.html">
            
            <a href="../chapter2/08_Enumerations.html">
                <i class="fa fa-check"></i> <b>2.8.</b> 枚举
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.9" data-path="chapter2/09_Classes_and_Structures.html">
            
            <a href="../chapter2/09_Classes_and_Structures.html">
                <i class="fa fa-check"></i> <b>2.9.</b> 类和结构体
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.10" data-path="chapter2/10_Properties.html">
            
            <a href="../chapter2/10_Properties.html">
                <i class="fa fa-check"></i> <b>2.10.</b> 属性
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.11" data-path="chapter2/11_Methods.html">
            
            <a href="../chapter2/11_Methods.html">
                <i class="fa fa-check"></i> <b>2.11.</b> 方法
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.12" data-path="chapter2/12_Subscripts.html">
            
            <a href="../chapter2/12_Subscripts.html">
                <i class="fa fa-check"></i> <b>2.12.</b> 附属脚本
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.13" data-path="chapter2/13_Inheritance.html">
            
            <a href="../chapter2/13_Inheritance.html">
                <i class="fa fa-check"></i> <b>2.13.</b> 继承
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.14" data-path="chapter2/14_Initialization.html">
            
            <a href="../chapter2/14_Initialization.html">
                <i class="fa fa-check"></i> <b>2.14.</b> 构造过程
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.15" data-path="chapter2/15_Deinitialization.html">
            
            <a href="../chapter2/15_Deinitialization.html">
                <i class="fa fa-check"></i> <b>2.15.</b> 析构过程
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.16" data-path="chapter2/16_Automatic_Reference_Counting.html">
            
            <a href="../chapter2/16_Automatic_Reference_Counting.html">
                <i class="fa fa-check"></i> <b>2.16.</b> 自动引用计数
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.17" data-path="chapter2/17_Optional_Chaining.html">
            
            <a href="../chapter2/17_Optional_Chaining.html">
                <i class="fa fa-check"></i> <b>2.17.</b> 可选链
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.18" data-path="chapter2/18_Type_Casting.html">
            
            <a href="../chapter2/18_Type_Casting.html">
                <i class="fa fa-check"></i> <b>2.18.</b> 类型检查
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.19" data-path="chapter2/19_Nested_Types.html">
            
            <a href="../chapter2/19_Nested_Types.html">
                <i class="fa fa-check"></i> <b>2.19.</b> 类型嵌套
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.20" data-path="chapter2/20_Extensions.html">
            
            <a href="../chapter2/20_Extensions.html">
                <i class="fa fa-check"></i> <b>2.20.</b> 扩展
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.21" data-path="chapter2/21_Protocols.html">
            
            <a href="../chapter2/21_Protocols.html">
                <i class="fa fa-check"></i> <b>2.21.</b> 协议
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.22" data-path="chapter2/22_Generics.html">
            
            <a href="../chapter2/22_Generics.html">
                <i class="fa fa-check"></i> <b>2.22.</b> 泛型
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.23" data-path="chapter2/23_Advanced_Operators.html">
            
            <a href="../chapter2/23_Advanced_Operators.html">
                <i class="fa fa-check"></i> <b>2.23.</b> 高级操作符
            </a>
            
            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="3" data-path="chapter3/chapter3.html">
            
            <a href="../chapter3/chapter3.html">
                <i class="fa fa-check"></i> <b>3.</b> 语言参考
            </a>
            
            
            <ul class="articles">
                
    
        <li class="chapter " data-level="3.1" data-path="chapter3/01_About_the_Language_Reference.html">
            
            <a href="../chapter3/01_About_the_Language_Reference.html">
                <i class="fa fa-check"></i> <b>3.1.</b> 关于语言参考
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="3.2" data-path="chapter3/02_Lexical_Structure.html">
            
            <a href="../chapter3/02_Lexical_Structure.html">
                <i class="fa fa-check"></i> <b>3.2.</b> 词法结构
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="3.3" data-path="chapter3/03_Types.html">
            
            <a href="../chapter3/03_Types.html">
                <i class="fa fa-check"></i> <b>3.3.</b> 类型
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="3.4" data-path="chapter3/04_Expressions.html">
            
            <a href="../chapter3/04_Expressions.html">
                <i class="fa fa-check"></i> <b>3.4.</b> 表达式
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="3.5" data-path="chapter3/10_Statements.html">
            
            <a href="../chapter3/10_Statements.html">
                <i class="fa fa-check"></i> <b>3.5.</b> 语句
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="3.6" data-path="chapter3/05_Declarations.html">
            
            <a href="../chapter3/05_Declarations.html">
                <i class="fa fa-check"></i> <b>3.6.</b> 声明
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="3.7" data-path="chapter3/06_Attributes.html">
            
            <a href="../chapter3/06_Attributes.html">
                <i class="fa fa-check"></i> <b>3.7.</b> 特性
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="3.8" data-path="chapter3/07_Patterns.html">
            
            <a href="../chapter3/07_Patterns.html">
                <i class="fa fa-check"></i> <b>3.8.</b> 模式
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="3.9" data-path="chapter3/08_Generic_Parameters_and_Arguments.html">
            
            <a href="../chapter3/08_Generic_Parameters_and_Arguments.html">
                <i class="fa fa-check"></i> <b>3.9.</b> 泛型参数
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="3.10" data-path="chapter3/09_Summary_of_the_Grammar.html">
            
            <a href="../chapter3/09_Summary_of_the_Grammar.html">
                <i class="fa fa-check"></i> <b>3.10.</b> 语法总结
            </a>
            
            
        </li>
    

            </ul>
            
        </li>
    


        
        <li class="divider"></li>
        <li>
            <a href="http://www.gitbook.io/" target="blank" class="gitbook-link">Generated using GitBook</a>
        </li>
<li style="margin-left:15%;"> <iframe  src="http://ghbtns.com/github-btn.html?user=numbbbbb&repo=the-swift-programming-language-in-chinese&type=watch&count=true&size=large"
  allowtransparency="true" frameborder="0" scrolling="0" width="170" height="30"></iframe></li>        
    </ul>
</div>

    <div class="book-body">
        <div class="body-inner">
            <div class="page-wrapper" tabindex="-1">
                <div class="book-progress">
    <div class="bar">
        <div class="inner" style="width: 21.05263157894737%;min-width: 18.42105263157895%;"></div>
    </div>
    <div class="chapters">
    
        <a href="../index.html" title="Introduction" class="chapter done new-chapter" data-progress="0" style="left: 0%;"></a>
    
        <a href="../chapter1/chapter1.html" title="欢迎使用 Swift" class="chapter done new-chapter" data-progress="1" style="left: 2.6315789473684212%;"></a>
    
        <a href="../chapter1/01_swift.html" title="关于 Swift" class="chapter done " data-progress="1.1" style="left: 5.2631578947368425%;"></a>
    
        <a href="../chapter1/02_a_swift_tour.html" title="Swift 初见" class="chapter done " data-progress="1.2" style="left: 7.894736842105263%;"></a>
    
        <a href="../chapter2/chapter2.html" title="Swift 教程" class="chapter done new-chapter" data-progress="2" style="left: 10.526315789473685%;"></a>
    
        <a href="../chapter2/01_The_Basics.html" title="基础部分" class="chapter done " data-progress="2.1" style="left: 13.157894736842104%;"></a>
    
        <a href="../chapter2/10_Properties.html" title="属性" class="chapter done " data-progress="2.10" style="left: 15.789473684210526%;"></a>
    
        <a href="../chapter2/11_Methods.html" title="方法" class="chapter done " data-progress="2.11" style="left: 18.42105263157895%;"></a>
    
        <a href="../chapter2/12_Subscripts.html" title="附属脚本" class="chapter done " data-progress="2.12" style="left: 21.05263157894737%;"></a>
    
        <a href="../chapter2/13_Inheritance.html" title="继承" class="chapter  " data-progress="2.13" style="left: 23.68421052631579%;"></a>
    
        <a href="../chapter2/14_Initialization.html" title="构造过程" class="chapter  " data-progress="2.14" style="left: 26.31578947368421%;"></a>
    
        <a href="../chapter2/15_Deinitialization.html" title="析构过程" class="chapter  " data-progress="2.15" style="left: 28.94736842105263%;"></a>
    
        <a href="../chapter2/16_Automatic_Reference_Counting.html" title="自动引用计数" class="chapter  " data-progress="2.16" style="left: 31.57894736842105%;"></a>
    
        <a href="../chapter2/17_Optional_Chaining.html" title="可选链" class="chapter  " data-progress="2.17" style="left: 34.21052631578947%;"></a>
    
        <a href="../chapter2/18_Type_Casting.html" title="类型检查" class="chapter  " data-progress="2.18" style="left: 36.8421052631579%;"></a>
    
        <a href="../chapter2/19_Nested_Types.html" title="类型嵌套" class="chapter  " data-progress="2.19" style="left: 39.473684210526315%;"></a>
    
        <a href="../chapter2/02_Basic_Operators.html" title="基本运算符" class="chapter  " data-progress="2.2" style="left: 42.10526315789474%;"></a>
    
        <a href="../chapter2/20_Extensions.html" title="扩展" class="chapter  " data-progress="2.20" style="left: 44.73684210526316%;"></a>
    
        <a href="../chapter2/21_Protocols.html" title="协议" class="chapter  " data-progress="2.21" style="left: 47.36842105263158%;"></a>
    
        <a href="../chapter2/22_Generics.html" title="泛型" class="chapter  " data-progress="2.22" style="left: 50%;"></a>
    
        <a href="../chapter2/23_Advanced_Operators.html" title="高级操作符" class="chapter  " data-progress="2.23" style="left: 52.63157894736842%;"></a>
    
        <a href="../chapter2/03_Strings_and_Characters.html" title="字符串和字符" class="chapter  " data-progress="2.3" style="left: 55.26315789473684%;"></a>
    
        <a href="../chapter2/04_Collection_Types.html" title="集合类型" class="chapter  " data-progress="2.4" style="left: 57.89473684210526%;"></a>
    
        <a href="../chapter2/05_Control_Flow.html" title="控制流" class="chapter  " data-progress="2.5" style="left: 60.526315789473685%;"></a>
    
        <a href="../chapter2/06_Functions.html" title="函数" class="chapter  " data-progress="2.6" style="left: 63.1578947368421%;"></a>
    
        <a href="../chapter2/07_Closures.html" title="闭包" class="chapter  " data-progress="2.7" style="left: 65.78947368421052%;"></a>
    
        <a href="../chapter2/08_Enumerations.html" title="枚举" class="chapter  " data-progress="2.8" style="left: 68.42105263157895%;"></a>
    
        <a href="../chapter2/09_Classes_and_Structures.html" title="类和结构体" class="chapter  " data-progress="2.9" style="left: 71.05263157894737%;"></a>
    
        <a href="../chapter3/chapter3.html" title="语言参考" class="chapter  new-chapter" data-progress="3" style="left: 73.6842105263158%;"></a>
    
        <a href="../chapter3/01_About_the_Language_Reference.html" title="关于语言参考" class="chapter  " data-progress="3.1" style="left: 76.3157894736842%;"></a>
    
        <a href="../chapter3/09_Summary_of_the_Grammar.html" title="语法总结" class="chapter  " data-progress="3.10" style="left: 78.94736842105263%;"></a>
    
        <a href="../chapter3/02_Lexical_Structure.html" title="词法结构" class="chapter  " data-progress="3.2" style="left: 81.57894736842105%;"></a>
    
        <a href="../chapter3/03_Types.html" title="类型" class="chapter  " data-progress="3.3" style="left: 84.21052631578948%;"></a>
    
        <a href="../chapter3/04_Expressions.html" title="表达式" class="chapter  " data-progress="3.4" style="left: 86.84210526315789%;"></a>
    
        <a href="../chapter3/10_Statements.html" title="语句" class="chapter  " data-progress="3.5" style="left: 89.47368421052632%;"></a>
    
        <a href="../chapter3/05_Declarations.html" title="声明" class="chapter  " data-progress="3.6" style="left: 92.10526315789474%;"></a>
    
        <a href="../chapter3/06_Attributes.html" title="特性" class="chapter  " data-progress="3.7" style="left: 94.73684210526316%;"></a>
    
        <a href="../chapter3/07_Patterns.html" title="模式" class="chapter  " data-progress="3.8" style="left: 97.36842105263158%;"></a>
    
        <a href="../chapter3/08_Generic_Parameters_and_Arguments.html" title="泛型参数" class="chapter  " data-progress="3.9" style="left: 100%;"></a>
    
    </div>
</div>

                <div class="page-inner">
                
                    <section class="normal" id="section-gitbook_6492">
                    
                        <blockquote>
<p>翻译：siemenliu</p>
<p>校对：zq54zquan</p>
</blockquote>
<h1 id="-subscripts-">附属脚本（Subscripts）</h1>
<hr>
<p>本页包含内容：</p>
<ul>
<li><a href="#subscript_syntax">附属脚本语法</a></li>
<li><a href="#subscript_usage">附属脚本用法</a></li>
<li><a href="#subscript_options">附属脚本选项</a></li>
</ul>
<p><em>附属脚本</em> 可以定义在类（Class）、结构体（structure）和枚举（enumeration）这些目标中，可以认为是访问对象、集合或序列的快捷方式，不需要再调用实例的特定的赋值和访问方法。举例来说，用附属脚本访问一个数组(Array)实例中的元素可以这样写 <code>someArray[index]</code> ，访问字典(Dictionary)实例中的元素可以这样写 <code>someDictionary[key]</code>。</p>
<p>对于同一个目标可以定义多个附属脚本，通过索引值类型的不同来进行重载，而且索引值的个数可以是多个。</p>
<blockquote>
<p>译者：这里附属脚本重载在本小节中原文并没有任何演示</p>
</blockquote>
<p><a name="subscript_syntax"></a></p>
<h2 id="-">附属脚本语法</h2>
<p>附属脚本允许你通过在实例后面的方括号中传入一个或者多个的索引值来对实例进行访问和赋值。语法类似于实例方法和计算型属性的混合。与定义实例方法类似，定义附属脚本使用<code>subscript</code>关键字，显式声明入参（一个或多个）和返回类型。与实例方法不同的是附属脚本可以设定为读写或只读。这种方式又有点像计算型属性的getter和setter：</p>
<pre><code>subscript(index: Int) -&gt; Int {
    get {
        // 返回与入参匹配的Int类型的值
    }

    set(newValue) {
        // 执行赋值操作
    }
}
</code></pre><p><code>newValue</code>的类型必须和附属脚本定义的返回类型相同。与计算型属性相同的是set的入参声明<code>newValue</code>就算不写，在set代码块中依然可以使用默认的<code>newValue</code>这个变量来访问新赋的值。</p>
<p>与只读计算型属性一样，可以直接将原本应该写在<code>get</code>代码块中的代码写在<code>subscript</code>中：</p>
<pre><code>subscript(index: Int) -&gt; Int {
    // 返回与入参匹配的Int类型的值
}
</code></pre><p>下面代码演示了一个在<code>TimesTable</code>结构体中使用只读附属脚本的用法，该结构体用来展示传入整数的<em>n</em>倍。</p>
<pre><code>struct TimesTable {
    let multiplier: Int
    subscript(index: Int) -&gt; Int {
        return multiplier * index
    }
}
let threeTimesTable = TimesTable(multiplier: 3)
println(&quot;3的6倍是\(threeTimesTable[6])&quot;)
// 输出 &quot;3的6倍是18&quot;
</code></pre><p>在上例中，通过<code>TimesTable</code>结构体创建了一个用来表示索引值三倍的实例。数值<code>3</code>作为结构体<code>构造函数</code>入参初始化实例成员<code>multiplier</code>。</p>
<p>你可以通过附属脚本来来得到结果，比如<code>threeTimesTable[6]</code>。这句话访问了<code>threeTimesTable</code>的第六个元素，返回<code>18</code>或者<code>6</code>的<code>3</code>倍。</p>
<blockquote>
<p>注意：</p>
<p><code>TimesTable</code>例子是基于一个固定的数学公式。它并不适合开放写权限来对<code>threeTimesTable[someIndex]</code>进行赋值操作，这也是为什么附属脚本只定义为只读的原因。</p>
</blockquote>
<p><a name="subscript_usage"></a></p>
<h2 id="-">附属脚本用法</h2>
<p>根据使用场景不同附属脚本也具有不同的含义。通常附属脚本是用来访问集合（collection），列表（list）或序列（sequence）中元素的快捷方式。你可以在你自己特定的类或结构体中自由的实现附属脚本来提供合适的功能。</p>
<p>例如，Swift 的字典（Dictionary）实现了通过附属脚本来对其实例中存放的值进行存取操作。在附属脚本中使用和字典索引相同类型的值，并且把一个字典值类型的值赋值给这个附属脚本来为字典设值：</p>
<pre><code>var numberOfLegs = [&quot;spider&quot;: 8, &quot;ant&quot;: 6, &quot;cat&quot;: 4]
numberOfLegs[&quot;bird&quot;] = 2
</code></pre><p>上例定义一个名为<code>numberOfLegs</code>的变量并用一个字典字面量初始化出了包含三对键值的字典实例。<code>numberOfLegs</code>的字典存放值类型推断为<code>Dictionary&lt;String, Int&gt;</code>。字典实例创建完成之后通过附属脚本的方式将整型值<code>2</code>赋值到字典实例的索引为<code>bird</code>的位置中。</p>
<p>更多关于字典（Dictionary）附属脚本的信息请参考<a href="../chapter2/04_Collection_Types.html">读取和修改字典</a></p>
<blockquote>
<p>注意：</p>
<p>Swift 中字典的附属脚本实现中，在<code>get</code>部分返回值是<code>Int?</code>，上例中的<code>numberOfLegs</code>字典通过下边返回的是一个<code>Int?</code>或者说“可选的int”，不是每个字典的索引都能得到一个整型值，对于没有设过值的索引的访问返回的结果就是<code>nil</code>；同样想要从字典实例中删除某个索引下的值也只需要给这个索引赋值为<code>nil</code>即可。</p>
</blockquote>
<p><a name="subscript_options"></a></p>
<h2 id="-">附属脚本选项</h2>
<p>附属脚本允许任意数量的入参索引，并且每个入参类型也没有限制。附属脚本的返回值也可以是任何类型。附属脚本可以使用变量参数和可变参数，但使用写入读出（in-out）参数或给参数设置默认值都是不允许的。</p>
<p>一个类或结构体可以根据自身需要提供多个附属脚本实现，在定义附属脚本时通过入参个类型进行区分，使用附属脚本时会自动匹配合适的附属脚本实现运行，这就是<em>附属脚本的重载</em>。</p>
<p>一个附属脚本入参是最常见的情况，但只要有合适的场景也可以定义多个附属脚本入参。如下例定义了一个<code>Matrix</code>结构体，将呈现一个<code>Double</code>类型的二维矩阵。<code>Matrix</code>结构体的附属脚本需要两个整型参数：</p>
<pre><code>struct Matrix {
    let rows: Int, columns: Int
    var grid: Double[]
    init(rows: Int, columns: Int) {
        self.rows = rows
        self.columns = columns
        grid = Array(count: rows * columns, repeatedValue: 0.0)
    }
    func indexIsValidForRow(row: Int, column: Int) -&gt; Bool {
        return row &gt;= 0 &amp;&amp; row &lt; rows &amp;&amp; column &gt;= 0 &amp;&amp; column &lt; columns
    }
    subscript(row: Int, column: Int) -&gt; Double {
        get {
            assert(indexIsValidForRow(row, column: column), &quot;Index out of range&quot;)
            return grid[(row * columns) + column]
        }
        set {
            assert(indexIsValidForRow(row, column: column), &quot;Index out of range&quot;)
            grid[(row * columns) + columns] = newValue
        }
    }
}
</code></pre><p><code>Matrix</code>提供了一个两个入参的构造方法，入参分别是<code>rows</code>和<code>columns</code>，创建了一个足够容纳<code>rows * columns</code>个数的<code>Double</code>类型数组。为了存储，将数组的大小和数组每个元素初始值0.0，都传入数组的构造方法中来创建一个正确大小的新数组。关于数组的构造方法和析构方法请参考<a href="../chapter2/04_Collection_Types.html">创建并且构造一个数组</a>。</p>
<p>你可以通过传入合适的<code>row</code>和<code>column</code>的数量来构造一个新的<code>Matrix</code>实例：</p>
<pre><code>var matrix = Matrix(rows: 2, columns: 2)
</code></pre><p>上例中创建了一个新的两行两列的<code>Matrix</code>实例。在阅读顺序从左上到右下的<code>Matrix</code>实例中的数组实例<code>grid</code>是矩阵二维数组的扁平化存储：</p>
<pre><code>// 示意图
grid = [0.0, 0.0, 0.0, 0.0]

        col0     col1
row0   [0.0,     0.0,
row1    0.0,     0.0]
</code></pre><p>将值赋给带有<code>row</code>和<code>column</code>附属脚本的<code>matrix</code>实例表达式可以完成赋值操作，附属脚本入参使用逗号分割</p>
<pre><code>matrix[0, 1] = 1.5
matrix[1, 0] = 3.2
</code></pre><p>上面两条语句分别<code>让matrix</code>的右上值为 1.5，坐下值为 3.2：</p>
<pre><code>[0.0, 1.5,
 3.2, 0.0]
</code></pre><p><code>Matrix</code>附属脚本的<code>getter</code>和<code>setter</code>中同时调用了附属脚本入参的<code>row</code>和<code>column</code>是否有效的判断。为了方便进行断言，<code>Matrix</code>包含了一个名为<code>indexIsValid</code>的成员方法，用来确认入参的<code>row</code>或<code>column</code>值是否会造成数组越界：</p>
<pre><code>func indexIsValidForRow(row: Int, column: Int) -&gt; Bool {
    return row &gt;= 0 &amp;&amp; row &lt; rows &amp;&amp; column &gt;= 0 &amp;&amp; column &lt; columns
}
</code></pre><p>断言在附属脚本越界时触发：</p>
<pre><code>let someValue = matrix[2, 2]
// 断言将会触发，因为 [2, 2] 已经超过了matrix的最大长度
</code></pre>
                    
                    </section>
                
                </div>
            </div>
        </div>

        
        <a href="../chapter2/11_Methods.html" class="navigation navigation-prev " aria-label="Previous page: 方法"><i class="fa fa-angle-left"></i></a>
        
        
        <a href="../chapter2/13_Inheritance.html" class="navigation navigation-next " aria-label="Next page: 继承"><i class="fa fa-angle-right"></i></a>
        
    </div>
</div>

        

        <script src="http://cdn.bootcss.com/ace/1.1.3/ace.js"></script>
        <script src="http://cdn.bootcss.com/ace/1.1.3/mode-javascript.js"></script>
        <script src="../gitbook/jsrepl/jsrepl.js" id="jsrepl-script"></script>
        <script src="../gitbook/app.js"></script>
        

    
    <script src="../gitbook/plugins/gitbook-plugin-mixpanel/plugin.js"></script>
    

    
    <script src="http://cdn.mathjax.org/mathjax/2.0-latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
    

    
    <script src="../gitbook/plugins/gitbook-plugin-mathjax/plugin.js"></script>
    

<script>
require(["gitbook"], function(gitbook) {
    var config = {};
    gitbook.start(config);
});
</script>

        
    </body>
    
</html>
